/**
 * 
 */
package patternRecognition.COMP6731.Assignment2;

/**
 * @author p_sokke
 *
 */
public class BinaryImagePreProcessing {
	public int[][] binaryImageSmoothing(int[][] binaryMatrix, int row, int column) {

		boolean isPixelChange;
		int filterValue = 0;
		do {
			isPixelChange = false;
			for (int x = row - 2; x > 0; x--) {
				for (int y = column - 2; y > 0; y--) {
					isPixelChange = isPixelChange
							|| smoothBinaryPoint(binaryMatrix, x, y, filterValue);
				}
			}

			filterValue++;
			filterValue = filterValue % 4;

		} while (isPixelChange);
		return binaryMatrix;
	}
	
	private static boolean smoothBinaryPoint(int[][] binaryMatrix, int x, int y, int filterValue) {

		if (filterValue == 0
				&& binaryMatrix[x][y - 1] == binaryMatrix[x - 1][y - 1]
				&& binaryMatrix[x - 1][y - 1] == binaryMatrix[x - 1][y]
				&& binaryMatrix[x - 1][y] == binaryMatrix[x - 1][y + 1]
				&& binaryMatrix[x - 1][y + 1] == binaryMatrix[x][y + 1]
				&& binaryMatrix[x][y] != binaryMatrix[x][y - 1]) {

			binaryMatrix[x][y] = binaryMatrix[x][y - 1];
			return true;
		}

		if (filterValue == 1
				&& binaryMatrix[x - 1][y] == binaryMatrix[x - 1][y + 1]
				&& binaryMatrix[x - 1][y + 1] == binaryMatrix[x][y + 1]
				&& binaryMatrix[x][y + 1] == binaryMatrix[x + 1][y + 1]
				&& binaryMatrix[x + 1][y + 1] == binaryMatrix[x + 1][y]
				&& binaryMatrix[x][y] != binaryMatrix[x - 1][y]) {

			binaryMatrix[x][y] = binaryMatrix[x - 1][y];
			return true;
		}

		if (filterValue == 2
				&& binaryMatrix[x][y + 1] == binaryMatrix[x + 1][y + 1]
				&& binaryMatrix[x + 1][y + 1] == binaryMatrix[x + 1][y]
				&& binaryMatrix[x + 1][y] == binaryMatrix[x + 1][y - 1]
				&& binaryMatrix[x + 1][y - 1] == binaryMatrix[x][y - 1]
				&& binaryMatrix[x][y] != binaryMatrix[x][y + 1]) {

			binaryMatrix[x][y] = binaryMatrix[x][y + 1];
			return true;
		}

		if (filterValue == 3
				&& binaryMatrix[x + 1][y] == binaryMatrix[x + 1][y - 1]
				&& binaryMatrix[x + 1][y - 1] == binaryMatrix[x][y - 1]
				&& binaryMatrix[x][y - 1] == binaryMatrix[x - 1][y - 1]
				&& binaryMatrix[x - 1][y - 1] == binaryMatrix[x - 1][y]
				&& binaryMatrix[x][y] != binaryMatrix[x + 1][y]) {

			binaryMatrix[x][y] = binaryMatrix[x + 1][y];
			return true;
		}

		return false;

	}
}
